<?php

namespace app\home\controller;

//引入公共控制器
use app\common\controller\Home;


//引入Thinkphp自带的数据库db类
use think\Db;

class Post extends Home
{
    // 构造函数
    public function __construct()
    {
        // 继承父类的构造函数
        parent::__construct();

        $this->PostModel = model('Post.Post');
    }


    // 发帖
    public function add()
    {


        // 判断是否有post过来的数据
        if ($this->request->isPost()) {

            // 接收验证码
            $vercode = $this->request->param('vercode', '');

            // 验证码
            if (!captcha_check($vercode)) {
                $this->error('验证码填写有误，请重新输入');
                exit;
            }

            // 判断是否有通过邮箱认证
            if (!$this->LoginUser['auth']) {
                $this->error('您为进行邮箱认证，请认证后在操作');
                exit;
            }


            // 加载三个模型
            $ModelPost = model('Post.Post');      //帖子发布表
            $ModelUser = model('User.User');      //用户表
            $ModelRecord = model('User.Record');  //用户消费记录表

            // 开启事务
            $ModelPost->startTrans();
            $ModelUser->startTrans();
            $ModelRecord->startTrans();

            // 发帖的逻辑
            // 1.判断积分是否充足
            // 2.发帖   pre_post
            // 3.扣积分=>用户表
            // 4.消费记录   

            // 判断用户积分是否充足
            $point = $this->request->param('point', 0);        //积分
            $state = $this->request->param('state', 0, 'trim'); //状态积分
            $StatePoint = 0;                                  //悬赏积分

            switch ($state) {
                    // 置顶
                case 1:
                    $StatePoint += 10;
                    break;
                    //精华
                case 2:
                    $StatePoint += 20;
                    break;
                    //热门
                case 3:
                    $StatePoint += 30;
                    break;
            }

            // 查询用户积分
            $UserPoint = $this->LoginUser['point'] ? (float)$this->LoginUser['point'] : 0;

            // 帖子的悬赏积分+状态积分   整个帖子消耗
            $PostPoint = bcadd($point, $StatePoint);

            // 判断用户积分是否够
            $UpdatePoint = bcsub($UserPoint, $PostPoint);

            if ($UpdatePoint < 0) {
                $this->error('积分不足请充值或签到');
                exit;
            }


            // 组装发帖的数据
            $PostData = [
                'title' => $this->request->param('title', '', 'trim'),
                'content' => $this->request->param('content', '', 'trim'),
                'point' => $point,
                'state' => $state,
                'userid' => $this->LoginUser['id'],
                'cateid' => $this->request->param('cateid', '', 'trim'),
            ];

            // 插入
            $PostStatus = $ModelPost->validate('common/Post/Post')->save($PostData);

            // 判断帖子是否插入成功
            if ($PostStatus === FALSE) {

                $this->error($ModelPost->getError());
                exit;
            }


            // 扣积分，更新用户表的point字段
            // 组装数据
            $UserData = [
                'id' => $this->LoginUser['id'],
                'point' => $UpdatePoint
            ];

            // 执行更新语句
            $UserStatus = $ModelUser->isUpdate(true)->save($UserData);

            // 更新用户积分失败
            if ($UserStatus === FALSE) {
                // 如果积分更新失败，帖子表要回滚
                $ModelPost->rollback();
                $this->error($ModelUser->getError());
                exit;
            }

            // 插入消费记录 pre_user_recode 
            // 组装数据
            $title = $this->request->param('title', '', 'trim');
            $RecordData = [
                'point' => $PostPoint,
                'content' => "您发布了：【{$title}】的悬赏帖子，消耗了【{$PostPoint}】个积分",
                'state' => 1,
                'userid' => $this->LoginUser['id']
            ];

            // 插入
            $RecordStatus = $ModelRecord->validate('common/User/Record')->save($RecordData);

            // 消费 记录插入失败
            if ($RecordStatus === FALSE) {
                // 回滚要按照顺序回滚
                $ModelUser->rollback();
                $ModelPost->rollback();
                $this->error($ModelRecord->getError());
                exit;
            }


            // 3给当中有一个失败就回滚
            if ($PostStatus === FALSE || $UserStatus === FALSE || $RecordStatus === FALSE) {
                // 回滚事务
                $ModelRecord->rollback();
                $ModelUser->rollback();
                $ModelPost->rollback();
                $this->error('发帖失败');
                exit;
            } else {
                // 发帖成功
                // 提交事务
                $ModelPost->commit();
                $ModelUser->commit();
                $ModelRecord->commit();
                $this->success('发帖成功', url('home/index/index'));
                exit;
            }
        }


        //查询所有的分类数据
        $catelist = Db::name("cate")->select();

        // 赋值给前台模板
        $this->view->assign('catelist', $catelist);

        //加载模板
        return $this->view->fetch();
    }

    // 编辑帖子
    public function edit()
    {
        // 接受参数
        $postid = $this->request->param('postid', 0);

        // 判断一下这个编辑的帖子是否存在
        $post = $this->PostModel->with(['user'])->find($postid);

        if (!$post) {
            $this->error('帖子不存在');
        }

        // 判断是否有post过来的数据
        if ($this->request->isPost()) {

            // 接受验证码
            $vercode = $this->request->param('vercode', '');
            // 验证码
            if (!captcha_check($vercode)) {
                $this->error('验证码填写有误，请重新输入');
                exit;
            }

            $title = $this->request->param('title', '', 'trim');
            $content = $this->request->param('content', '', 'trim');
            $cateid = $this->request->param('cateid', '', 'trim');

            // 组装数据
            $PostData = [
                'id' => $post['id'],
                'title' => $title,
                'content' => $content,
                'cateid' => $cateid,
            ];


            //自定义验证规则
            $validate = [
                //规则
                [
                    'title' => 'require',
                    'content' => 'require',
                    'cateid' => 'require',
                ],
                //提示
                [
                    'title.require'  => '帖子标题必填',
                    'content.require'  => '帖子正文内容必填',
                    'cateid.require'  => '请选择帖子分类',
                ]
            ];

            // 更新数据库  ...$validate=$validate[0],$validate[1]
            $result = $this->PostModel->validate(...$validate)->isUpdate(true)->save($PostData);

            if ($result == FALSE) {
                $this->error($this->PostModel->getError());
            } else {
                $this->success('编辑帖子成功', url('home/index/info', ['postid' => $post['id']]));
                exit;
            }
        }

        //查询所有的分类数据
        $catelist = Db::name("cate")->select();
        // var_dump($catelist);
        // exit;

        //赋值给前台模板
        $this->view->assign('catelist', $catelist);
        $this->view->assign('post', $post);

        // 加载模板
        return $this->view->fetch();
    }

    // 删除帖子
    public function del()
    {
        // 接受ajax传过来的参数
        $postid = $this->request->param('postid', 0);

        // 判断一下这个帖子是否存在
        $post = $this->PostModel->with(['user'])->find($postid);

        if (!$post) {
            $this->error('帖子不存在');
        }

        // 软删除
        $result = $this->PostModel->destroy($postid);

        if ($result === FALSE) {
            $this->error($this->PostModel->getError());
            exit;
        } else {
            $this->success('删除帖子成功');
            exit;
        }
    }

}
